package cn.mesmile.thread.pool;

import java.util.concurrent.*;

/**
 * @author zb
 * @date 2020/12/31 9:46
 * @Description 线程池
 */
public class ThreadPool {

    /**
     *  corePoolSize:核心池的大小
     *  maximumPoolSize:最大线程数
     *  keepAliveTime：线程没有任务时最多保持多长时间后会终止
     *
     *  Executors.newCachedThreadPool()	创建一个可根据需要创建新线程的线程池
     *  Executors.newFixedThreadPool(n)	创建一个可重用固定线程数的线程池
     *  Executors.newSingleThreadExecutor()	:创建一个只有一个线程的线程池
     *  Executors.newScheduledThreadPool(n)	创建一个线程池，它可安排在给定延迟后运行命令或者定期地执行。
     */
    public static void main(String[] args) {

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(">>>>>>> 执行计划项目");
            }
        },10L,TimeUnit.SECONDS);

        System.out.println("后续执行 <<<<<<<<<");
        // 关闭线程池
        scheduledExecutorService.shutdown();
    }


    public static void singleThreadExecutor(){
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(">>>>>>>>>>>>>>>>>>>");
                    System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
                }
            });
        }
        System.out.println("************************");
        executorService.shutdown();
    }



    public static void testStr(){
        long startTime = System.currentTimeMillis();

        Future<String> submit = null;

        // 创建一个可根据需要创建新线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        // 创建一个可根据需要创建新线程的线程池
        // ExecutorService executorService = Executors.newCachedThreadPool();


        CountDownLatch countDownLatch = new CountDownLatch(20);

        for (int i = 0; i < 20; i++) {
            //创建一个可根据需要创建新线程的线程池
            submit = executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(1000L);
                    System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());

                    countDownLatch.countDown();

                    return "success";
                }
            });
        }

        try {
            countDownLatch.await();
            // 获取结果
            System.out.println("submit.get() = " + submit.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();

//        executorService.shutdown();

        System.out.println("(endTime - startTime) = " + (endTime - startTime));
    }


}
